<?php

namespace App\Http\Controllers\Article;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Tags;
use App\Models\Type;
use App\Models\Studying;
use App\Models\Collect;
use App\Models\PushLog;
use App\Models\Article;
use App\Models\ArticleRecommend;
use App\Models\ArticleComment;
use App\Models\ArticleSelected;
use App\Models\Users;
use App\User;
use App\Contant\TagsType;
use App\Utils\FileUploader;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\Banner;
use App\Models\Consultation;
use Illuminate\Support\Facades\Input;
use App\Events\WxMessagePush;
use App\Contant\WxMessageType;
use App\Events\WxCustomerMessagePush;
use App\Models\Special;


class ArticleController extends Controller
{
    protected $ret;

	public function __construct()
    {
        $request   = $_SERVER['QUERY_STRING'];   //url参数
    	$this->ret = [];
        $this->ret['request'] = $request;
    }
    //20180925 文章分类管理
    public function Types(){
    	$Type = new Type();
		$data = $Type->getList("ARTICLE");  //获取文章类别

		$this->ret['data']= $data;
    	return view("article.types", $this->ret);
    }

    //20180925 文章类别添加
    public function typeAdd(){

    	return view("article.typeadd");
    }

    //20180925 执行文章类别添加
    public function typeInsert(Request $request){
    	$id = $request->input("id");
    	if($id){
    		//echo $id;
            $type = Type::where('id',$id)->first();
        }else{
            $type = new Type();
        }
        $type->title = $request->input("title");
        $type->model = "ARTICLE";  //默认文章
        $type->state = $request->input("state");
        $type->is_index  = $request->input("is_index");
        $type->cover_url = $request->input("cover_url");
        $type->seo_title = $request->input("seo_title");
        $type->seo_description = $request->input("seo_description");
        $result = $type->save();
       	if($result){
           return redirect('/type/list');
        }
    }

    //20180925 文章类别编辑
    public function typeEdit($id){
    	$type = Type::where("id",$id)->first();
    	$this->ret['item'] = $type;
    	return view("article.typeedit", $this->ret);
    }

    //20180925  修改文章类别状态
    public function typeState(Request $request){
    	$id = $request->input("id");
    	$state = $request->input("state");

    	$type = Type::where('id',$id)->first();
    	$type->state = $state;
    	$result = $type->save();
       	if($result){
           return redirect('/type/list');
        }
    }

    //20180925  修改文章类别是否首页显示
    public function typeIsindex(Request $request){
    	$id = $request->input("id");
    	$isindex = $request->input("isindex");

    	$type = Type::where('id',$id)->first();
    	$type->is_index = $isindex;
    	$result = $type->save();
       	if($result){
           return redirect('/type/list');
        }
    }

    //20180926
    public function articleList(Request $request){
        $title    = $request->input('title','');
        $is_video = $request->input('is_video',0);
        $list  = new Article();
        $Type     = new Type();
        if($title){
            $list = $list->where('title','like',"%{$title}%");
            echo 111;
        }

        $list = $list->where("is_video", $is_video)->orderBy("orderby","desc")->orderBy('id','desc')->paginate(10);
        $types = $Type->getListState("ARTICLE");  //获取文章类别

        $this->ret['list']  = $list;
        $this->ret['title'] = $title;
        $this->ret['is_video'] = $is_video;
        $this->ret['types'] = $types;
        return view("article.articlelist", $this->ret);
    }

    //20180926 新增文章页面
    public function articleAdd(){
        $Type  = new Type();
        $types = $Type->getListState("ARTICLE");  //获取文章类别
        $tags  = Tags::where('state',1)->where('type',TagsType::ARTICLE)->select('id','title')->get();
        $special = Special::whereNull("deleted_at")->where("state","1")->select("id","title")->get();
       
        $this->ret['types']= $types;
        $this->ret['tags'] = $tags;
        $this->ret['special'] = $special;
        return view("article.articleadd", $this->ret);
    }

   /* 
     * 20180927
     * 编辑文章
     */
    public function articleEdit(Request $request){
        $Type  = new Type();
        $types = $Type->getListState("ARTICLE");  //获取文章类别
        $tags  = Tags::where('state',1)->where('type',TagsType::ARTICLE)->select('id','title')->get();
        $id    = $request->input("id");
        $article = Article::where("id", $id)->first();
        $special = Special::whereNull("deleted_at")->where("state","1")->select("id","title")->get();
        if($article->type_ids){
            $type_ids = explode(',', $article->type_ids);
        }else{
            $type_ids = [];
        }
        if($article->tag_ids){
            $tag_ids = explode(',', $article->tag_ids);
        }else{
            $tag_ids = [];
        }
        if($article->special_id){
            $special_id = explode(',', $article->special_id);
        }else{
            $special_id = [];
        }
        $this->ret['types']= $types;
        $this->ret['tags'] = $tags;
        $this->ret['article'] = $article;
        $this->ret['type_ids']= $type_ids;
        $this->ret['tag_ids'] = $tag_ids;
        $this->ret['special_id'] = $special_id;
        $this->ret['special'] = $special;
        return view("article.articleedit", $this->ret);
    }

    //20180926 文章执行更新或新增
    public function articleInsert(Request $request){
        $data = $request->input();
        $id   = $request->input("id");
        if($id){
            $article = Article::where("id", $data['id'])->first();
            $article->opertion_user_id = $request->user()->id;
            $article->user_id = $data['author'];
        }else{
            $article = new Article();
            $article->user_id = $data['author'];
            $article->opertion_user_id = $request->user()->id;
        }
        if(!empty($data['types'])){
            $article->type_ids = implode(",", $data['types']);
        }
        if(!empty($data['tags'])){
            $article->tag_ids  = implode(",", $data['tags']);
        }
        if(!empty($data['special_id'])){
            $article->special_id  = implode(",", $data['special_id']);
        }
        $article->title = $data['title'];
        $article->likes = $data['likes'];
        $article->views = $data['views'];
        $article->orderby = $data['orderby'];
        $article->content = $data['content'];
        $article->is_video    = $data['is_video'];
        $article->video_url   = $data['video_url'];
        $article->cover_url   = $data['cover_url'];
        $article->bill_img    = $data['bill_img'];
        $article->description = $data['description'];
        $article->seo_title   = $data['seo_title'];
        $article->seo_description  = $data['seo_description'];
        $article->is_recommend     = $data['is_recommend'];
       

        if($id && $data['today_selected']==""){
            $today = $article->today_selected;
            $article->today_selected  = $data['today_selected'];
            $del   = 1;
        }else{
            $article->today_selected  = $data['today_selected'];
            $today = $data['today_selected'];
            $del   = 0;
        }
            
        $result = $article->save();
        if($result){
            //post_baidu($article->id, "article");  //自动发送给百度熊掌号
            $ArticleSelected = new ArticleSelected();
            if($today){
                $ArticleSelected->addOne($today, $article->id, $request->user()->id, $del);
            }
            return redirect('/article/list');
        }
    }

    //20181114 测试自动发送资源给百度熊掌号
    public function post_baidu($article_id){
        $urls = array(
            'http://m.saipubbs.com/article/detail/'.$article_id.'.html',
        );

        $api = 'http://data.zz.baidu.com/urls?appid=1615100668980398&token=cQYoU0uzUHbi8m0f&type=realtime';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        //print_r($result);
        logger()->info($result);
    }

    /* 
     * 20180926
     * ajax修改文章状态
     */
    public function changeState(Request $request){
        $id    = $request->input('id');
        $state = $request->input('state');
        $article = Article::where('id',$id)->first();
        $article->state  = $state;
        if($article->save()){
            return $this->getMessage(0,'修改成功');
        }else{
            return $this->getMessage(1,'修改状态失败');
        }
    }

     /* 
     * 20180926
     * ajax修改文章是否首页显示
     */
    public function changeIndex(Request $request){
        $id    = $request->input('id');
        $state = $request->input('state');
        $article = Article::where('id',$id)->first();
        $article->is_index  = $state;
        if($article->save()){
            return $this->getMessage(0,'修改成功');
        }else{
            return $this->getMessage(1,'修改状态失败');
        }
    }
    
    /* 
     * 20180926
     * ajax修改文章是否设置精选
     */
    public function changeSelected(Request $request){
        $id    = $request->input('id');
        $state = $request->input('state');
        $article = Article::where('id',$id)->first();
        $article->is_selected  = $state;
        if($article->save()){
            return $this->getMessage(0,'修改成功');
        }else{
            return $this->getMessage(1,'修改状态失败');
        }
    }

    /* 
     * 20180926
     * 删除文章（整体）
     */
    public function delete(Request $request){
        $id = $request->input('id');
        $result = Article::where('id',$id)->delete();

        if($result){
            return $this->getMessage(0,'删除成功');
        }else{
            return $this->getMessage(1,'删除失败');
        }
    }


    /* 
     * 20181023
     * 推荐文章列表
     */
    public function recommendList(Request $request){
        $title = $request->input('title','');
        $state = $request->input("state", 2);
        $article  = new ArticleRecommend();
        if($title){
            $article = $article->where('title','like',"%{$title}%");
        }
        if($state<2){
            $article = $article->where("state", $state);
        }
        $list = $article->orderBy('id','desc')->paginate(10);
        $this->ret['list']  = $list;
        $this->ret['title'] = $title;
        return view("article.recommendlist", $this->ret);
    }

    /* 
     * 20181023
     * 修改推荐文章状态
     */
    public function recommendState(Request $request){
        $id = $request->input('id','');
        $state = $request->input("state");
        $article  = new ArticleRecommend();
        if($id){
            $article = ArticleRecommend::where("id", $id)->first();
            $article->state = $state;
            $article->save();
        }
        
        return redirect('/article/recommend');
    }

    /* 
     * 20181029
     * 添加评论页面
     */
    public function addComment(Request $request){
        $id    = $request->input("id");
        $article = Article::where("id", $id)->first();
        $this->ret['article'] = $article;
        return view("article.addcomment", $this->ret);
    }

    /* 
     * 20181029
     * 执行添加评论
     */
    public function insertComment(Request $request){
        $article_id = $request->input("id");
        $user_id    = $request->input("author");
        $content    = $request->input("content");
        $user       = DB::table("users")->where("id", $user_id)->select("name")->first();
        $comment    = new ArticleComment();
        $comment->article_id= $article_id;
        $comment->user_id   = $user_id;
        $comment->content   = $content;
        $comment->user_name = $user->name;
        $comment->is_true   = 0;
        $r = $comment->save();
        return redirect('/article/addcomment?id='.$article_id);
    }

    /*
    * 文章选择
    */
    public function articleChoose(Request $request){
        $title = $request->input('title','');
        $special_id = $request->input('special_id');
        $articles = new Article();
        if($title){
            $articles = $articles->where('title','like','%'.$title.'%');
        }
        if($special_id){
            $articles = $articles->where('special_id',$special_id);
        }
        $articles = $articles->where('state',1)->paginate(10);
        return json_encode(['code'=>0,'body'=>view('article.modal.articleBody',['articles'=>$articles,'title'=>$title,'special_id'=>$special_id])->render()]);
    }

    /*
     * 文章专栏选择
     */
    public function themeChoose(Request $request){

        $title = $request->input('title','');
        $specials = new Special();
        if($title){
            $specials = $specials->where('title','like','%'.$title.'%');
        }
        $specials = $specials->where('state',1)->paginate(10);
        return json_encode(['code'=>0,'body'=>view('article.modal.specialBody',['specials'=>$specials,'title'=>$title])->render()]);
    }

    /*
     * 信息推送
     */
    public function dealMessagePush(Request $request){
        $type = $request->input('type');
        $class_id = $request->input('id');
        $startTime = $request->input('startTime','');
        $endTime = $request->input('endTime','');
        $courseId = $request->input('courseId','');
        $courseClass = CourseClass::where('id',$class_id)->first();

        $author = $courseClass->author;
        $info = $this->getInfo($type,$author);
        if($type == WxMessageType::WEIXINNOTICE){
            $title = "孕产教练交流群上线了";
        }elseif($type == WxMessageType::COURSEBUY){
            $title = "【新课推荐】".$courseClass->title;
        }else{
            $title = "【".WxMessageType::trans($type)."】".$courseClass->title;
        }

        $data['type'] = WxMessageType::IMAGE;
        $push_message = $courseClass->push_message.
            "\n";
        if($type != WxMessageType::CREATE){
            $push_message = '';
        }
        if($info !=''){
            $info = $info."\n";
        }
        if($type == WxMessageType::WEIXINNOTICE){
            $desc = '加微信号：SPJSSQ，加入孕产教练交流群与田坤导师互动交流~';
            $url = env('PT_WEB_URL').'/course/detail/42.html';
        }else {
            $desc = $author->name . "[导师系列课]：\n" . $info . $push_message . "点击进入即可查看系列课内容\n回复[TD" . $courseClass->id . "]不再接收该导师系列课推送";
            $url = env('PT_WEB_URL').'/course/detail/'.$class_id.'.html';
        }
        $data['list'] = [[
            "title"=>$title,
            "description"=>$desc,
            "url"=>$url,
            "picurl"=>'http://image.saipubbs.com/'.$courseClass->explain_url]];

        $fans = $this->getPushUsers($type,$courseClass,$author,$startTime,$endTime,$courseId);

        foreach($fans as $fan){
            $data['openid'] = $fan->openid;
//            dd($fan);
            event(new WxCustomerMessagePush($data));
        }
        $pushLog = new PushLog();
        $pushLog->course_class_id = $courseClass->id;
        $pushLog->type = $type;
        $pushLog->description = WxMessageType::trans($type);
        $pushLog->start = $startTime;
        $pushLog->end = $endTime;
        $pushLog->save();

        return $this->getMessage(0,'推送成功');
    }

}
